import React from 'react';
import { useNavigate } from 'react-router-dom';
import { request } from '@/utils/request';
import { useI18n, toApiLanguageCode } from '@/utils/in18';

// 角色选择子组件

type CategoryType = 'real_male' | 'real_female' | 'anime_male' | 'anime_female' | '';

interface TemplateItem {
    id?: number;
    name?: string;
    image_url?: string;
    // 可能还有其它字段，例如 key_words 等，根据接口 information 返回
    key_words?: string;
}

interface ApiListResponse<T> {
    success: boolean;
    data: T[];
    total?: number;
    page?: number;
    page_size?: number;
}

const PAGE_SIZE = 10; // 接口要求每页 4 条

interface SelectBackgroundProps {
    // 选择回调：在作为弹窗使用时由父组件传入
    onSelect?: (item: TemplateItem) => void;
    // 关闭回调
    onClose?: () => void;
    // 可选：传入所属 category，用于请求时传 Belongs
    belongs?: string | null;
}

const SelectBackground: React.FC<SelectBackgroundProps> = ({ onSelect, onClose, belongs }) => {
    const navigate = useNavigate();
    const { locale, t } = useI18n();

    // 查询参数状态
    const [category, setCategory] = React.useState<CategoryType>('');
    const [page, setPage] = React.useState(1);

    // 列表状态
    const [items, setItems] = React.useState<TemplateItem[]>([]);
    const [total, setTotal] = React.useState(0);
    const [loading, setLoading] = React.useState(false);
    const scrollRef = React.useRef<HTMLDivElement | null>(null);
    const fetchingRef = React.useRef(false);
    const sentinelRef = React.useRef<HTMLDivElement | null>(null);
    const initializedRef = React.useRef(false); // 首次页加载完成前，禁止 IO 触发翻页，避免竞态
    const lastRequestIdRef = React.useRef(0); // 忽略过期请求，防止乱序导致的闪烁/重复

    // 请求函数：根据当前筛选与分页请求列表
    const fetchList = React.useCallback(async () => {
        const currentRequestId = ++lastRequestIdRef.current;
        setLoading(true);
        fetchingRef.current = true;
        try {
            // 语言参数由 axios 拦截器自动注入，此处仍按需求显式传参以更安全
            const res = await request.post<ApiListResponse<TemplateItem>>(
                '/api/accessory/getAccessoriesRoute',
                {

                    type: "background",
                    page,
                    page_size: PAGE_SIZE,
                    language: toApiLanguageCode(locale as any),// 语言按产品约定：xby(西) fy(法) jp(日) en(英) ey(俄)
                }
            );
            const { data, total: t = 0 } = res?.data || ({} as any);
            const list = Array.isArray(data) ? data : [];

            // 仅处理最新请求的结果，忽略过期响应
            if (currentRequestId !== lastRequestIdRef.current) return;

            setItems((prev) => {
                const merged = page === 1 ? list : [...prev, ...list];
                // 依据 id 优先去重，其次使用 image_url/name 兜底，避免重复闪烁
                const seen = new Set<string | number>();
                const deduped: TemplateItem[] = [];
                for (const item of merged) {
                    const key = (item.id ?? item.image_url ?? item.name ?? '') as any;
                    if (!seen.has(key)) {
                        seen.add(key);
                        deduped.push(item);
                    }
                }
                return deduped;
            });
            setTotal(t || 0);
            if (page === 1) initializedRef.current = true;
        } catch (e) {
            // 仅在当前为最新请求且拉取第一页失败时清空，避免闪烁
            if (currentRequestId === lastRequestIdRef.current) {
                if (page === 1) setItems([]);
                setTotal(0);
            }
        } finally {
            // 仅在当前为最新请求时落下 loading 状态，避免被过期请求覆盖
            if (currentRequestId === lastRequestIdRef.current) setLoading(false);
            fetchingRef.current = false;
        }
    }, [category, page, locale]);

    // 打开即请求 + 依赖变化时请求
    React.useEffect(() => {
        fetchList();
    }, [fetchList]);

    // 点击卡片：回传所需字段并返回生成页
    const handleSelect = (item: TemplateItem) => {
        const state: any = {
            image_url: item?.image_url || '',
            name: item?.name || '',
            id: item?.id,
            key_words: item?.key_words,
        };
        // 弹窗模式：回调给父组件
        if (onSelect) {
            onSelect(item);
            if (onClose) onClose();
            return;
        }
        // 路由模式：返回上一页并携带 state
        try {
            // 避免类型报错，直接使用原生 history 返回
            (window.history as History).back();
        } catch {
            navigate('/creatImages', { state });
        }
    };

    // 渲染顶部工具栏（搜索条视觉，无输入交互）
    const Toolbar = (
        <div style={{ borderBottom: "1px solid #2C2C2C" }} className='px-3 pt-3 pb-2 sticky top-0 z-10 bg-[#0b0b0b] md:bg-[#0b0b0b]'>
            <div className='flex items-center'>
                <div className='flex-1 text-[16px] font-semibold text-center'>{t('CreatImg.background')}</div>
                {/* close */}
                <button className='ml-2 w-10 h-full text-[2rem] absolute right-3 text-[#e5e7eb]' onClick={() => { if (onClose) onClose(); else { try { (window.history as History).back(); } catch { navigate('/creatImages'); } } }} >
                    {t('loginModel.close')}
                </button>
            </div>
        </div>
    );

    // 渲染网格
    const Grid = (
        <div style={{ borderTop: "1px solid #2C2C2C", zIndex: 9999 }} className='px-3 pb-6 mt-3 py-3 '>
            {/* 保持网格常驻，减少加载时的闪烁 */}
            {loading && items.length === 0 && (
                <div className='text-center text-[#9ea3a8] py-3'>{t('CreatImg.loading')}</div>
            )}
            <div className='grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 gap-2 md:gap-3 lg:gap-4'>
                {items.map((it, idx) => (
                    <button
                        key={it.id ? String(it.id) : (it.image_url ? `img:${it.image_url}` : (it.name ? `name:${it.name}` : `i:${idx}`))}
                        className='relative overflow-hidden bg-[#111]'
                        onClick={() => handleSelect(it)}
                    >
                        {/* 头像 */}
                        <div style={{ aspectRatio: '4 / 7', width: '100%', position: 'relative', backgroundColor: '#111' }} className='flex items-center justify-center'>
                            <img
                                src={(it.image_url || '').trim()}
                                alt={it.name || t('CreatImg.alt_character')}
                                // 保证完整显示，不裁剪
                                className='w-full h-full rounded-[0.5rem]'
                                style={{ objectFit: 'contain', display: 'block' }}
                                loading='lazy'
                            />
                        </div>
                        {/* 名称 */}
                        {/* <div className='absolute  left-1 bottom-1 right-1 text-center'>
                            <span className='px-2 py-1 rounded bg-black/60 text-white text-xs font-semibold truncate inline-block max-w-full'>
                                {it.name || t('my_liked_persion.unnamed_template')}
                            </span>
                        </div> */}
                    </button>
                ))}
            </div>

            {/* 加载提示 + sentinel 用于 IntersectionObserver 触发懒加载 */}
            <div className='mt-4 flex justify-center items-center text-sm text-[#cbd0d5]'>
                {items.length < total ? (loading ? t('CreatImg.loading') : t('CreatImg.pull_to_load_more')) : t('CreatImg.no_more')}
            </div>
            <div ref={sentinelRef} style={{ height: 1 }} />
        </div>
    );

    // 当弹窗打开时锁定 body 滚动，防止父容器滚动（同时处理移动端 touchmove）
    React.useEffect(() => {
        const prevOverflow = document.body.style.overflow;
        const prevPaddingRight = document.body.style.paddingRight;
        const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
        if (scrollbarWidth > 0) document.body.style.paddingRight = `${scrollbarWidth}px`;
        document.body.style.overflow = 'hidden';

        // 只在非 modal 区域阻止 touchmove，允许 modal 内部滚动
        const touchHandler = (e: TouchEvent) => {
            const tgt = e.target as Node | null;
            if (scrollRef.current && tgt && scrollRef.current.contains(tgt)) {
                // 在 modal 内容内，允许滚动
                return;
            }
            e.preventDefault();
        };
        document.addEventListener('touchmove', touchHandler as EventListener, { passive: false });

        return () => {
            document.body.style.overflow = prevOverflow;
            document.body.style.paddingRight = prevPaddingRight;
            document.removeEventListener('touchmove', touchHandler as EventListener);
        };
    }, []);

    // 使用 IntersectionObserver 监听底部 sentinel，实现懒加载（比 scroll 事件更可靠）
    React.useEffect(() => {
        const sentinel = sentinelRef.current;
        const root = scrollRef.current;
        if (!sentinel || !root) return;
        const io = new IntersectionObserver((entries) => {
            for (const entry of entries) {
                if (entry.isIntersecting) {
                    const hasMore = items.length < total;
                    if (hasMore && !fetchingRef.current && initializedRef.current && !loading) {
                        setPage((p) => p + 1);
                    }
                }
            }
        }, { root, rootMargin: '120px' });
        io.observe(sentinel);
        return () => io.disconnect();
    }, [items.length, total, loading]);

    // 切换筛选时，重置初始化标记并回到顶部，不清空 items 以避免闪烁
    React.useEffect(() => {
        initializedRef.current = false;
        if (scrollRef.current) {
            try { scrollRef.current.scrollTo({ top: 0, behavior: 'auto' }); } catch { }
        }
    }, [category]);

    return (
        <div style={{ zIndex: 9999 }} className='fixed inset-0 z-50 bg-black/70 flex items-start justify-center md:p-6' onClick={() => { if (onClose) onClose(); }}>
            <div style={{ borderTop: "1px solid #2C2C2C", borderBottom: "1px solid #2C2C2C" }} className='bg-[#0b0b0b] w-[100vw] md:w-[92vw] lg:w-[86vw] xl:w-[80vw] 2xl:w-[70vw] max-w-[1400px] h-[85vh] md:h-[88vh] lg:h-[90vh] mt-2 overflow-hidden flex flex-col rounded-none md:rounded-2xl' onClick={(e) => e.stopPropagation()}>
                {Toolbar}
                <div ref={scrollRef} className='flex-1 overflow-y-auto'>
                    {Grid}
                </div>
            </div>
        </div>
    );
};

export default SelectBackground;


